//
//  LoginViewController.m
//  PurchasingMeeting
//
//  Created by zhuang yihang on 7/11/13.
//  Copyright (c) 2013 YX. All rights reserved.
//

#import "LoginViewController.h"
#import "DataManager.h"
#import "AppManager.h"
#import "UserObject.h"
#import "UIHelper.h"
#import "PMGlobal.h"
#import "WaitTooles.h"
#import "MainViewController.h"
#import "Reachability.h"
#import "WebServiceManager.h"
//#import "ZXingWidgetController.h"
//#import "QRCodeReader.h"
//#import "MultiFormatOneDReader.h"
#import "AnalysisViewController.h"
#import "ProductViewController.h"
#import "SuitViewController.h"
#import "StatisticViewController.h"
#import "HelpViewController.h"
#import "MainType1ViewController.h"

#import "SDImageView+SDWebCache.h"

#define SHOP_RETRY 3

@interface LoginViewController (){
    UITextField *userTextField;
    UITextField *passwordTextField;
    UIImageView *login;
    
    
    int shopRetry;
}

@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:)
                                                     name:UIKeyboardWillHideNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hidden:) name:@"hidden" object:nil];
    }
    return self;
}



- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    shopRetry = SHOP_RETRY;
    UIView *v = [[UIView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:v];
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    [v addGestureRecognizer:tapGr];
    

    
    UIImage *img = [[UIHelper getInstance] getBundleImage:@"view_bg.png"];
    UIImageView *back = [[UIImageView alloc] init];
    
#ifdef DHH_iOS
    back.frame = CGRectMake(0, 0, self.view.width,self.view.height);
#else
    back.frame = CGRectMake(0, 0, 1024,748);
#endif
    back.backgroundColor = [UIColor colorWithPatternImage:img];
    [self.view addSubview:back];
    
    
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    title.text = @"数字订货会";
    title.backgroundColor = [UIColor clearColor];
    
#ifdef DHH_iOS
    title.font = [[PMGlobal getInstance] getBoldPhoneFont:30];
#else
    title.font = [[PMGlobal getInstance] getBoldPhoneFont:50];
#endif
    [title sizeToFit];
    
    
    title.textColor = [[UIHelper getInstance] getColorbyRed:15 Green:125 Blue:201 Alpha:255];
    title.center = CGPointMake(back.width/2, 100);
    title.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:title];
    
#ifdef DHH_iOS
    img = [[UIHelper getInstance] getBundleImage:@"login_bg_iphone.jpg"];
    login = [[UIImageView alloc]initWithImage:img];
    login.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    // login.center = CGPointMake(back.width/2, back.height/2-10);
    login.userInteractionEnabled = YES;
    [self.view addSubview:login];
    /*
    img = [[UIHelper getInstance] getBundleImage:@"login_bg_iphone1.png"];
    UIImageView *loginview = [[UIImageView alloc]initWithImage:img];
    loginview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    loginview.center = CGPointMake(self.view.width/2, self.view.height/2);
    loginview.userInteractionEnabled = YES;
    [login addSubview:loginview];
     */
#else
    img = [[UIHelper getInstance] getBundleImage:@"login_bg_ipad.jpg"];
    login = [[UIImageView alloc]initWithImage:img];
    login.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    // login.center = CGPointMake(back.width/2, back.height/2-10);
    login.userInteractionEnabled = YES;
    [self.view addSubview:login];
#endif
    
    NSString *bundlePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:CUSTOMER_PATH];
    NSString *plistname = [NSString stringWithFormat:@"%@.plist",CUSTOMER_NAME];
    NSString *filename = [bundlePath stringByAppendingPathComponent:plistname];
    NSDictionary *d = [NSDictionary dictionaryWithContentsOfFile:filename];
    
#ifdef DHH_iOS
    NSDictionary *dic = [d objectForKey:@"iphone"];
    NSString *usertextfont = [dic objectForKey:@"usertextfont"];
    NSString *usertextcenterx = [dic objectForKey:@"usertextcenterx"];
    NSString *usertextcentery = [dic objectForKey:@"usertextcentery"];
    userTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 180, 30)];
    userTextField.font = [[PMGlobal getInstance] getPhoneFont:[usertextfont intValue]];
    userTextField.center =CGPointMake([usertextcenterx intValue], [usertextcentery intValue]);
    [login addSubview:userTextField];
#else
    NSDictionary *ipaddic = [d objectForKey:@"ipad"];
    NSDictionary *dic = [ipaddic objectForKey:@"loginview"];
    if ([[dic objectForKey:@"havesmallimage"] boolValue]==YES) {
        img = [[UIHelper getInstance] getBundleImage:@"login_smallimage.png"];
        smallimage = [[UIImageView alloc]initWithImage:img];
        smallimage.frame = CGRectMake(0, 0, img.size.width, img.size.height);
//        smallimage.center = CGPointMake(750, 384);
        smallimage.center = CGPointMake(self.view.width/2, self.view.height/2);
        smallimage.userInteractionEnabled = YES;
        [self.view addSubview:smallimage];
    }
    NSString *usertextfont = [dic objectForKey:@"usertextfont"];
    NSString *usertextcenterx = [dic objectForKey:@"usertextcenterx"];
    NSString *usertextcentery = [dic objectForKey:@"usertextcentery"];
    userTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 330, 35)];
    userTextField.font = [[PMGlobal getInstance] getPhoneFont:[usertextfont intValue]];
    userTextField.center =CGPointMake([usertextcenterx intValue], [usertextcentery intValue]);
    if ([[dic objectForKey:@"havesmallimage"] boolValue]==YES) {
        [smallimage addSubview:userTextField];
    }
    else
    {
        [login addSubview:userTextField];
    }
#endif
    userTextField.delegate = self;
    //text.returnKeyType = UIReturnKeyGo;
    userTextField.backgroundColor = [UIColor clearColor];
    
    userTextField.placeholder = @"请输入用户名";
    userTextField.borderStyle = UITextBorderStyleNone;
    userTextField.delegate = self;
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSString *usernamestr = [def objectForKey:@"username"];
//    NSString *passwordstr = [def objectForKey:@"password"];
    if (usernamestr) {
        userTextField.text=usernamestr;
    }
    else
    {
#ifdef DEBUG
        userTextField.text = DEBUG_USERNAME;
#endif
    }

    userTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    userTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    userTextField.returnKeyType = UIReturnKeyDone;
    
    
    passwordTextField = [[UITextField alloc] initWithFrame:userTextField.bounds];
    NSString *passwordtextcenterx = [dic objectForKey:@"passwordtextcenterx"];
    NSString *passwordtextcentery = [dic objectForKey:@"passwordtextcentery"];
    passwordTextField.center =CGPointMake([passwordtextcenterx intValue], [passwordtextcentery intValue]);
    
    if ([[dic objectForKey:@"havesmallimage"] boolValue]==YES) {
        [smallimage addSubview:passwordTextField];
    }
    else
    {
        [login addSubview:passwordTextField];
    }
    passwordTextField.font = userTextField.font;
    passwordTextField.delegate = self;
    passwordTextField.secureTextEntry = YES;

    passwordTextField.backgroundColor = [UIColor clearColor];

    passwordTextField.placeholder = @"请输入密码";
    passwordTextField.borderStyle = UITextBorderStyleNone;
    passwordTextField.delegate = self;
    passwordTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    passwordTextField.returnKeyType = UIReturnKeyDone;
    /*
    if (passwordstr) {
        password.text=passwordstr;
    }
    else
    {
#ifdef DEBUG
        password.text = @"2222";
#endif
    }
*/
    passwordTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    
    
    UIButton *loginbtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
#ifdef DHH_iOS
    NSString *logininterval = [dic objectForKey:@"logininterval"];
    img = [[UIHelper getInstance] getBundleImage:@"login_signIn_iphone.png"];
    loginbtn.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    loginbtn.center = CGPointMake(login.width/2-[logininterval intValue], 295);
    [loginbtn setBackgroundImage:img forState:UIControlStateNormal];
    
    [loginbtn addTarget:self action:@selector(userlogin) forControlEvents:UIControlEventTouchUpInside];
    
    [login addSubview:loginbtn];
#else
    NSString *loginbottom = [dic objectForKey:@"loginbottom"];
    NSString *logininterval = [dic objectForKey:@"logininterval"];
    NSString *loginbtnwidth = [dic objectForKey:@"loginbtnwidth"];
    NSString *loginbtnheight = [dic objectForKey:@"loginbtnheight"];
    img = [[UIHelper getInstance] getBundleImage:@"anniu1.png"];
    if ([loginbtnwidth intValue]!=0) {
        loginbtn.frame = CGRectMake(0, 0, [loginbtnwidth intValue], [loginbtnheight intValue]);
    }
    else
    {
        loginbtn.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    }
    [loginbtn setBackgroundImage:img forState:UIControlStateNormal];
    [loginbtn setTitle:@"登陆" forState:UIControlStateNormal];
    [loginbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [loginbtn addTarget:self action:@selector(userlogin) forControlEvents:UIControlEventTouchUpInside];
    
    if ([[dic objectForKey:@"havesmallimage"] boolValue]==YES) {
        [smallimage addSubview:loginbtn];
        loginbtn.center = CGPointMake(smallimage.width/2-[logininterval intValue], 450);
    }
    else
    {
        loginbtn.center = CGPointMake(login.width/2-[logininterval intValue], 450);
        [login addSubview:loginbtn];
    }
    loginbtn.bottom = [loginbottom intValue];
#endif
    UIButton *zbarloginbtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
#ifdef DHH_iOS
    img = [[UIHelper getInstance] getBundleImage:@"zbarloginbtn_iphone.png"];
    zbarloginbtn.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    zbarloginbtn.center = CGPointMake(login.width/2+[logininterval intValue], 285);
    [zbarloginbtn setBackgroundImage:img forState:UIControlStateNormal];
    zbarloginbtn.bottom = loginbtn.bottom;
   // [zbarloginbtn setTitle:@"二维码登录" forState:UIControlStateNormal];
    
    [zbarloginbtn addTarget:self action:@selector(zbar:) forControlEvents:UIControlEventTouchUpInside];
    
    [login addSubview:zbarloginbtn];
#else
    img = [[UIHelper getInstance] getBundleImage:@"anniu1.png"];
    if ([loginbtnwidth intValue]!=0) {
        zbarloginbtn.frame = CGRectMake(0, 0, [loginbtnwidth intValue], [loginbtnheight intValue]);
    }
    else
    {
        zbarloginbtn.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    }
    [zbarloginbtn setBackgroundImage:img forState:UIControlStateNormal];
    [zbarloginbtn setTitle:@"二维码登陆" forState:UIControlStateNormal];
    [zbarloginbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [zbarloginbtn addTarget:self action:@selector(zbar:) forControlEvents:UIControlEventTouchUpInside];
    
    if ([[dic objectForKey:@"havesmallimage"] boolValue]==YES) {
        [smallimage addSubview:zbarloginbtn];
        zbarloginbtn.center = CGPointMake(smallimage.width/2+[logininterval intValue], 450);
    }
    else
    {
        zbarloginbtn.center = CGPointMake(login.width/2+[logininterval intValue], 450);
        [login addSubview:zbarloginbtn];
    }
    zbarloginbtn.bottom = loginbtn.bottom;
#endif
    
#if DEBUG
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 150, 50);
    btn.center = CGPointMake(50, 700);
    btn.backgroundColor = [UIColor grayColor];
    [btn setTitle:@"清除账号绑定设备" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(clearuser:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
#endif
    
    UILabel *l = [[UILabel  alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
    [self.view addSubview:l];
    l.right = 1000;
    l.bottom = 748;
    l.textAlignment = NSTextAlignmentRight;
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *appVersion = [infoDic objectForKey:@"CFBundleVersion"];
    l.text = [NSString stringWithFormat:@"%@",appVersion];
    l.backgroundColor = [UIColor clearColor];
    
    [[WebServiceManager sharedManager] SyncPic:^(NSArray *response) {
        [[PMGlobal getInstance] saveImageConfig:response];
        
        NSString *path = [[PMGlobal getInstance] getImageConfigUrl:@"Login"];
        [login setImageWithURL:[NSURL URLWithString:path] block:nil];
    }];
}


#pragma mark -
//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    // if(offset > 0)
#ifdef DHH_iOS
    self.view.frame = CGRectMake(0.0f, -80, self.view.frame.size.width, self.view.frame.size.height);
#else
    self.view.frame = CGRectMake(0.0f, -150, self.view.frame.size.width, self.view.frame.size.height);
#endif
  //  login.frame = CGRectMake(0.0f, -96, imageview.frame.size.width, imageview.frame.size.height);
  //  textimageview.center = CGPointMake(self.view.width/2, 140);
  //  text.top = 83;
   // logintext.top = text.bottom+4;
   // passwordtext.top = logintext.bottom+4;
   // signIn.top = passwordtext.bottom +10;
    
    [UIView commitAnimations];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [passwordTextField resignFirstResponder];
    [userTextField resignFirstResponder];
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
    return YES;
}
//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    /*
     self.view.frame =CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height);
     imageview.frame = CGRectMake(0, 0, imageview.frame.size.width, imageview.frame.size.height);
     textimageview.center = CGPointMake(self.view.width/2, 257);
     text.top = 200;
     logintext.top = text.bottom+4;
     passwordtext.top = logintext.bottom+4;
     isclick = NO;
     */
}

#pragma mark 隐藏键盘通知
-(void)keyboardWillHide:(NSNotification *)sender
{
    [userTextField resignFirstResponder];
    [passwordTextField resignFirstResponder];
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
}

-(void)viewTapped:(UITapGestureRecognizer*)tapGr {
    [userTextField resignFirstResponder];
    [passwordTextField resignFirstResponder];
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// Applications should use supportedInterfaceOrientations and/or shouldAutorotate..
#ifndef DHH_iOS
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
    return UIInterfaceOrientationIsLandscape(toInterfaceOrientation);
}

- (BOOL)shouldAutorotate{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskLandscape;
}

#endif

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1) {
        NSString *pwd1 = [alertView textFieldAtIndex:0].text;
        NSString *pwd2 = [alertView textFieldAtIndex:1].text;
        if (![pwd1 isEqualToString:pwd2]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"错误" message:@"两次密码不一致，请重新输入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            
            [alert textFieldAtIndex:0].text = @"";
            [alert textFieldAtIndex:1].text = @"";
            return;
        }else{
//            [[WebServiceManager sharedManager] setNewPassword:(NSString *)user password:(NSString *)password completion:];
            [self performSelectorOnMainThread:@selector(modifyPwd:) withObject:pwd2 waitUntilDone:YES];
        }
    }
}

- (void)modifyPwd:(NSString *)p{
    [WaitTooles showHUD:@"正在修改密码..."];
    [[WebServiceManager sharedManager] setNewPassword:userTextField.text
                                             password:p completion:^(id res){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"密码修改成功" message:@"请重新登录" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        passwordTextField.text = p;
    }];
}
-(void)userlogin{
    [userTextField resignFirstResponder];
    [passwordTextField resignFirstResponder];
    
    [WaitTooles showHUD:@"正在登录..."];
    [[WebServiceManager sharedManager] checkID:^(NSString *response) {
        
        if (response.length>0) {
//            NSString *ver = [[NSUserDefaults standardUserDefaults] objectForKey:@"order_version"];
            
            [[NSUserDefaults standardUserDefaults] setObject:response forKey:@"order_version"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        
        [[PMGlobal getInstance] isWifiOn:^(id res){
            if (res){
                [[PMGlobal getInstance] setNetworkFlag:1];
                [self loginOnline:userTextField.text password:passwordTextField.text];
            }else{
                [[PMGlobal getInstance] setNetworkFlag:0];
                [self loginOffline:userTextField.text password:passwordTextField.text];
            }
        }];
    }];

}


- (void)loginOnline:(NSString *)user password:(NSString *)password{
    [[WebServiceManager sharedManager] login:user password:password u_id:nil completion:^(NSDictionary *response){
        [WaitTooles removeHUD];
        NSString *canlogin = [response objectForKey:@"CanLogin"];
        if ([canlogin isEqualToString:@"False"]) {
            NSString *msg = [response objectForKey:@"Message"];
            showMessage(msg);
            return;
        }
        NSArray *arr = [response objectForKey:@"Table"];
        if ( arr==nil ) {
            if (response) {
                NSString *msg = [response objectForKey:@"Message"];
                showMessage(msg);
                return ;
            }else{
                showMessage(@"网络不给力，请稍后再试");
                return;
            }
        }else{
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:[arr objectAtIndex:0]];
            
            //[dic removeObjectForKey:@"u_id"];
            
            NSString *shopid = [dic objectForKey:@"shopid"];
            NSString *shopname = [dic objectForKey:@"shopname"];
            NSString *usercode = [dic objectForKey:@"usercode"];
            NSString *username = [dic objectForKey:@"username"];
            
            //是否重置密码
            if ( [[dic objectForKey:@"ReSetPW"] intValue]==1) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入新密码" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认",nil, nil];
                alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
                [alert textFieldAtIndex:0].placeholder = @"请输入新密码";
                [alert textFieldAtIndex:0].secureTextEntry = YES;
                [alert textFieldAtIndex:1].placeholder = @"请再输入一次密码";
                [alert show];
                return;
            }
            
            NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
            
            NSString *endTime = [dic objectForKey:@"dtEndTime"];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            dateFormatter.dateFormat = @"yyyyMMdd";
            NSDate *expire = [dateFormatter dateFromString:endTime];
            
            [def setObject:endTime forKey:@"expire_date"];
            
            NSDate *now = [NSDate date];
            if ([now compare:expire]==NSOrderedDescending) {
                showMessage(@"软件已过期，如有问题，请联系我们");
                [def setObject:[NSNumber numberWithBool:YES] forKey:@"is_expire"];
                [def synchronize];
                return;
            }else{
                [def setObject:[NSNumber numberWithBool:NO] forKey:@"is_expire"];
                [def synchronize];
            }
            
            
            [WaitTooles showHUD:@"登录成功，获取您的订单信息..."];
            
            [[DataManager sharedManager] addUser:usercode name:username password:password u_id:nil shopid:shopid shopname:shopname];
            
            ShopObject *obj = [[ShopObject alloc] init];
            obj.shopID = shopid;
            obj.shopName = shopname;
            NSArray *array = [NSArray arrayWithObject:obj];
            [[DataManager sharedManager] setUserObject:usercode name:username u_id:nil shop:array password:password];
            
            NSString *biURL = [dic objectForKey:@"serveraddress"];
            NSString *checkCode = [dic objectForKey:@"u_id"];
            
            [[DataManager sharedManager] getUserObject].biURL = [NSString stringWithFormat:@"%@_%@",biURL,checkCode];
            [[DataManager sharedManager] getUserObject].inputType = [[dic objectForKey:@"iInputType"] intValue];
            
            [[AppManager sharedManager] setUpdateInterval:[[dic objectForKey:@"SpdmTime"] floatValue]];
            [[AppManager sharedManager] setSubmitInterval:[[dic objectForKey:@"OrderTime"] floatValue]];
            [[PMGlobal getInstance] enableImage:[[dic objectForKey:@"ShowPhoto"] boolValue]];
            
#ifdef DEBUG
            NSString *url = [dic objectForKey:@"serverip"];
#else
            NSString *url = [dic objectForKey:@"serverip"];
#endif
            NSString *address = [NSString stringWithFormat:@"%@/Service.aspx",url];
            [[DataManager sharedManager]setnewServerIP:address];
            [[WebServiceManager sharedManager]setnewServerIP:YES];
            
            [self getshops:usercode
                  password:password
                  username:username
                      u_id:nil
                       dic:dic];
            
            return;
        }
    }];
}

- (void)loginOffline:(NSString *)user password:(NSString *)password{
    
    [WaitTooles removeHUD];
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSNumber *expire = [def objectForKey:@"is_expire"];
    if (expire!=nil&&[expire boolValue]==YES) {
        showMessage(@"软件已过期，如有问题，请联系我们");
        return;
    }
    
    
    NSString *s = [def objectForKey:@"expire_date"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyyMMdd";
    NSDate *expireDate = [dateFormatter dateFromString:s];
    if ([expireDate compare:[NSDate date]] == NSOrderedAscending) {
        [def setObject:[NSNumber numberWithBool:YES] forKey:@"is_expire"];
        [def synchronize];
        showMessage(@"软件已过期，如有问题，请联系我们");
        return;
    }

    
    [WaitTooles removeHUD];
    
    NSArray *shops = [[DataManager sharedManager]getShopObjects:user];
    [[DataManager sharedManager] setShopList:shops];
    
    NSString *username = [[DataManager sharedManager]getusername:user];
    [[DataManager sharedManager] setUserObject:user
                                          name:username
                                          u_id:nil shop:shops
                                      password:password];
    UserObject *obj = [[DataManager sharedManager] getUserObject];
    obj.biURL = [[DataManager sharedManager]getbiurl:user];
    obj.inputType = [[[DataManager sharedManager]getinputtype:user]intValue];
    
    [[PMGlobal getInstance] enableImage:[[def objectForKey:@"ShowPhoto"] boolValue]];
    
    if ([[DataManager sharedManager]checkusercode:user password:password]) {
        [self loginSuccessfully];
    }else{
        if ([[DataManager sharedManager] userExist:user]) {
            showMessage(@"当前网路不可用，首次登录需要联网");
        }else{
            showMessage(@"用户名或密码不正确");
        }
        
    }

}


- (void)login:(NSString *)textstr password:(NSString *)passwordstr u_id:(NSString *)u_id{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    [def setObject:[NSNumber numberWithBool:NO] forKey:@"has_expired"];
    if (![def objectForKey:@"has_expired"]){
    
        NSDate *d = [NSDate date];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSDate *expire = [dateFormatter dateFromString:@"2014-9-1 00:00:00"];
        if ([d compare:expire]==NSOrderedDescending) {
            NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
            [def setObject:[NSNumber numberWithBool:YES] forKey:@"has_expired"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"app_has_expired" object:nil];
            
            UIAlertView* alert = [[UIAlertView alloc]initWithTitle:nil message:@"应用已过期，无法登陆"
                                                          delegate:nil cancelButtonTitle:@"确定"
                                                 otherButtonTitles:nil];
            [alert show];
            return;
        }
    }
    /*
    else if ([def objectForKey:@"has_expired"]&&[def objectForKey:@"has_expired"]) {
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:nil message:@"应用已过期，无法登陆"
                                                      delegate:nil cancelButtonTitle:@"确定"
                                             otherButtonTitles:nil];
        [alert show];
        return;
    }
    */
    if ([textstr isEqualToString:@"000"]&&[passwordstr isEqualToString:@"000"]) {
        [userTextField resignFirstResponder];
        [passwordTextField resignFirstResponder];
        
        ShopObject *obj = [[DataManager sharedManager] getShopObject:textstr];
        NSString *name = [[DataManager sharedManager] getUserNameByLocal:textstr];
        NSArray *array = [NSArray arrayWithObject:obj];
        [[DataManager sharedManager] setUserObject:textstr name:name u_id:u_id shop:array password:passwordstr];
        [self loginSuccessfully];
    }

    else if ([[PMGlobal getInstance]networkFlag]) {
    
        [WaitTooles showHUD:@"正在登录..."];
        [[WebServiceManager sharedManager] login:textstr password:passwordstr u_id:u_id completion:^(NSDictionary *response){
            [WaitTooles removeHUD];
            NSArray *arr = [response objectForKey:@"Table"];
            if ( arr==nil) {
                UIAlertView *alert;
                if (response) {
                    /*
                    if ([[response objectForKey:@"Result"]isEqual:@"False"]) {
                        alert = [[UIAlertView alloc]initWithTitle:nil message:@"用户名或密码不正确"
                                                         delegate:nil cancelButtonTitle:@"确定"
                                                otherButtonTitles:nil];
                    }
                    else if([[response objectForKey:@"Result"]isEqual:@"Disabled"]){
                        alert = [[UIAlertView alloc]initWithTitle:nil message:@"用户已禁用"
                                                         delegate:nil cancelButtonTitle:@"确定"
                                                otherButtonTitles:nil];
                    }
                     */
                    alert = [[UIAlertView alloc]initWithTitle:nil message:[response objectForKey:@"Message"]
                                                     delegate:nil cancelButtonTitle:@"确定"
                                            otherButtonTitles:nil];
                    [alert show];
                    
                    return ;
                }
                else{

                }
                
            }else{
                NSDictionary *dic = [arr objectAtIndex:0];
                
                NSString *shopid = [dic objectForKey:@"shopid"];
                NSString *shopname = [dic objectForKey:@"shopname"];
                NSString *usercode = [dic objectForKey:@"usercode"];
                NSString *username = [dic objectForKey:@"username"];
                
                if ( [[dic objectForKey:@"ReSetPW"] intValue]==1) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入新密码" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认",nil, nil];
                    alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
                    [alert textFieldAtIndex:0].placeholder = @"请输入新密码";
                    [alert textFieldAtIndex:0].secureTextEntry = YES;
                    [alert textFieldAtIndex:1].placeholder = @"请再输入一次密码";
                    [alert show];
                    return;
                    
                }
                
            
                [WaitTooles showHUD:@"登录成功，获取您的订单信息..."];
                
                [[DataManager sharedManager] addUser:usercode name:username password:passwordstr u_id:u_id shopid:shopid shopname:shopname];
                
                ShopObject *obj = [[ShopObject alloc] init];
                obj.shopID = shopid;
                obj.shopName = shopname;
                NSArray *array = [NSArray arrayWithObject:obj];
                [[DataManager sharedManager] setUserObject:usercode name:username u_id:u_id shop:array password:passwordstr];
                
                NSString *biURL = [dic objectForKey:@"serveraddress"];
                NSString *checkCode = [dic objectForKey:@"u_id"];
                
                [[DataManager sharedManager] getUserObject].biURL = [NSString stringWithFormat:@"%@_%@",biURL,checkCode];
                [[DataManager sharedManager] getUserObject].inputType = [[dic objectForKey:@"iInputType"] intValue];
                NSString *url = [dic objectForKey:@"serverip"];
                NSString *address = [NSString stringWithFormat:@"%@/Service.aspx",url];
                [[DataManager sharedManager]setnewServerIP:address];
                [[WebServiceManager sharedManager]setnewServerIP:YES];
                
                [[PMGlobal getInstance] enableImage:[[dic objectForKey:@"ShowPhoto"] boolValue]];
                
                [self getshops:usercode password:passwordstr username:username u_id:u_id dic:dic];
                
                return;
            }
            
        }];
        
        return;


    }

    else{
        /*
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:nil message:@"网络连接失败"
                                         delegate:nil cancelButtonTitle:@"确定"
                                otherButtonTitles:nil];
        [alert show];
         */
        [userTextField resignFirstResponder];
        [passwordTextField resignFirstResponder];
        
        
        if (u_id) {
            textstr = [[DataManager sharedManager] getUserCode:u_id];
        }
        
        NSArray *shops = [[DataManager sharedManager]getShopObjects:textstr];
        [[DataManager sharedManager] setShopList:shops];

        NSString *username = [[DataManager sharedManager]getusername:textstr];
        [[DataManager sharedManager] setUserObject:textstr name:username u_id:u_id shop:shops password:passwordstr];
        [[DataManager sharedManager] getUserObject].biURL = [[DataManager sharedManager]getbiurl:textstr];
        [[DataManager sharedManager] getUserObject].inputType = [[[DataManager sharedManager]getinputtype:textstr]intValue];

        
        if ([[DataManager sharedManager]checkusercode:textstr password:passwordstr]) {
            [WaitTooles removeHUD];
            [self loginSuccessfully];
        }
        else
        {
            UIAlertView* alert = [[UIAlertView alloc]initWithTitle:nil message:@"用户名或密码不正确"
                                                          delegate:nil cancelButtonTitle:@"确定"
                                                 otherButtonTitles:nil];
            [alert show];
        }
    }
}


- (void)exit{

    showMessage(@"网络链接出错，请重新打开程序");
    [WaitTooles showHUD:@"网络链接出错，请重新打开程序"];
    runBlockAfterDelay(2, ^(){
        exit(0);
    });
}

-(void)getshops:(NSString *)usercode password:(NSString *)passwordstr username:(NSString *)username u_id:(NSString *)u_id dic:(NSDictionary *)dic
{
    [[WebServiceManager sharedManager ] getShopList:usercode completion:^(NSDictionary *shops){
        NSArray *arr = [shops objectForKey:@"Table"];
        
        if (shopRetry==0) {
            showMessage(@"获取店铺列表失败，请稍后再试");
            shopRetry = SHOP_RETRY;
            [self performSelector:@selector(exit) withObject:nil afterDelay:2];
            return;
        }
        
        shopRetry--;
        if (arr.count==0) {
            sleep(1);
            [self getshops:usercode password:passwordstr username:username u_id:u_id dic:dic];
        }
        else
        {
            shopRetry = SHOP_RETRY;
            NSMutableArray *shopsArray = [NSMutableArray array];
            [[DataManager sharedManager]deleteuserandshops:usercode password:passwordstr];
            for ( NSDictionary *dic in arr ) {
                if (dic.allKeys.count==0) {
                    continue;
                }
                ShopObject *obj = [[ShopObject alloc] init];
                obj.shopID = [dic objectForKey:@"shopid"];
                obj.shopName = [dic objectForKey:@"shopname"];
                obj.bOrder = [dic objectForKey:@"bOrder"];
                obj.bCheck = [[dic objectForKey:@"bCheck"] intValue];
                [shopsArray addObject:obj];
                [[DataManager sharedManager]adduserandshops:usercode password:passwordstr username:[[DataManager sharedManager] getUserObject].userName biurl:[[DataManager sharedManager] getUserObject].biURL inputtype:[[DataManager sharedManager] getUserObject].inputType shops:dic];
            }
            [[DataManager sharedManager] setShopList:shopsArray];
            [[DataManager sharedManager] setCurrentShop:nil];
            
            [[DataManager sharedManager] setUserObject:usercode name:username u_id:u_id shop:shopsArray password:passwordstr];
            NSString *biURL = [dic objectForKey:@"serveraddress"];
            NSString *checkCode = [dic objectForKey:@"u_id"];
            
            [[DataManager sharedManager] getUserObject].biURL = [NSString stringWithFormat:@"%@_%@",biURL,checkCode];
            [[DataManager sharedManager] getUserObject].inputType = [[dic objectForKey:@"iInputType"] intValue];
            [WaitTooles removeHUD];
            [self loginSuccessfully];
        }
    }];
}

-(void)zbar:(UIButton *)sender
{
    //    ZbarViewController *zbar = [[ZbarViewController alloc]init];
    //    [self.navigationController pushViewController:zbar animated:YES];
    
//    ZBarReaderViewController *reader = [ZBarReaderViewController new];
//    reader.readerDelegate = self;
//    reader.supportedOrientationsMask = ZBarOrientationMaskAll;
//#ifdef DHH_iOS
//    UIImage *img = [[UIHelper getInstance] getBundleImage:@"croprect_iphone.png"];
//    UIImageView *imageview = [[UIImageView alloc]initWithImage:img];
//    imageview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
//    imageview.center = CGPointMake(160, 190);
//    [reader.view addSubview:imageview];
//    
//    img = [[UIHelper getInstance] getBundleImage:@"croptip_iphone.png"];
//    UIImageView *tipimageview = [[UIImageView alloc]initWithImage:img];
//    tipimageview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
//    tipimageview.centerX = imageview.centerX;
//    tipimageview.top = imageview.bottom;
//    [reader.view addSubview:tipimageview];
//#else
//    UIImage *img = [[UIHelper getInstance] getBundleImage:@"croprect.png"];
//    UIImageView *imageview = [[UIImageView alloc]initWithImage:img];
//    imageview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
//    imageview.center = CGPointMake(512, 368);
//    [reader.view addSubview:imageview];
//    
//    img = [[UIHelper getInstance] getBundleImage:@"croptip.png"];
//    UIImageView *tipimageview = [[UIImageView alloc]initWithImage:img];
//    tipimageview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
//    tipimageview.centerX = imageview.centerX;
//    tipimageview.top = imageview.bottom;
//    [reader.view addSubview:tipimageview];
//#endif
//    CGRect scanMaskRect;
//    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0)
//    {
//        scanMaskRect = CGRectMake(0, 0, imageview.size.width, imageview.size.height);
//    }
//    else
//    {
//        scanMaskRect = CGRectMake(0, 0, 1024, 768);
//    }
//    reader.scanCrop = [self getScanCrop:scanMaskRect readerViewBounds:reader.view.bounds];
//    
//    ZBarImageScanner *scanner = reader.scanner;
//    
//    [scanner setSymbology: ZBAR_I25
//                   config: ZBAR_CFG_ENABLE
//                       to: 0];
//    /*
//    ZBarReaderView *readerView = [[ZBarReaderView alloc]init];
//    readerView.frame =CGRectMake(0,0, self.view.frame.size.width,self.view.frame.size.height);
//    readerView.readerDelegate = self;
//    //关闭闪光灯
//    readerView.torchMode =0;
//    //扫描区域
//    CGRect scanMaskRect = CGRectMake(60, 140, 260, 260);
//    
//    //处理模拟器
//    if (TARGET_IPHONE_SIMULATOR) {
//        ZBarCameraSimulator *cameraSimulator
//        = [[ZBarCameraSimulator alloc]initWithViewController:self];
//        cameraSimulator.readerView = readerView;
//    }
//    [self.view addSubview:readerView];
//    [self.view sendSubviewToBack:readerView];
//    //扫描区域计算
//    readerView.scanCrop = [self getScanCrop:scanMaskRect readerViewBounds:readerView.bounds];
//    
//    [readerView start];
//    */
//    
//    [self presentModalViewController: reader
//                            animated: YES];

}
//- (void) imagePickerController: (UIImagePickerController*) reader
// didFinishPickingMediaWithInfo: (NSDictionary*) info
//{
//    id<NSFastEnumeration> results =
//    [info objectForKey: ZBarReaderControllerResults];
//    ZBarSymbol *symbol = nil;
//    for(symbol in results)
//        break;
//    
//    zbarimageview.image =
//    [info objectForKey: UIImagePickerControllerOriginalImage];
//    
//    [reader dismissModalViewControllerAnimated: YES];
//    
//    //判断是否包含 头'http:'
//    NSString *regex = @"http+:[^\\s]*";
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
//    
//    //判断是否包含 头'ssid:'
//    NSString *ssid = @"ssid+:[^\\s]*";;
//    NSPredicate *ssidPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",ssid];
//    
//    
//    [WaitTooles showHUD:@"正在登录..."];
//    [[PMGlobal getInstance] isWifiOn:^(id res){
//        if (res) {
//            [[PMGlobal getInstance] setNetworkFlag:1];
//        }else{
//            [[PMGlobal getInstance] setNetworkFlag:0];
//        }
//        [self login:nil password:nil u_id:symbol.data];
//        [WaitTooles removeHUD];
//    }];
//    
//    
//
//    if ([predicate evaluateWithObject:zbarlabel.text]) {
//        
//        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:nil
//                                                        message:@"It will use the browser to this URL。"
//                                                       delegate:nil
//                                              cancelButtonTitle:@"Close"
//                                              otherButtonTitles:@"Ok", nil];
//        alert.delegate = self;
//        alert.tag=1;
//        [alert show];
//        
//        
//        
//    }
//    else if([ssidPre evaluateWithObject:zbarlabel.text]){
//        
//        NSArray *arr = [zbarlabel.text componentsSeparatedByString:@";"];
//        
//        NSArray * arrInfoHead = [[arr objectAtIndex:0] componentsSeparatedByString:@":"];
//        
//        NSArray * arrInfoFoot = [[arr objectAtIndex:1] componentsSeparatedByString:@":"];
//        
//        
//        zbarlabel.text=
//        [NSString stringWithFormat:@"ssid: %@ \n password:%@",
//         [arrInfoHead objectAtIndex:1],[arrInfoFoot objectAtIndex:1]];
//        
//        
//        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:zbarlabel.text
//                                                        message:@"The password is copied to the clipboard , it will be redirected to the network settings interface"
//                                                       delegate:nil
//                                              cancelButtonTitle:@"Close"
//                                              otherButtonTitles:@"Ok", nil];
//        
//        
//        alert.delegate = self;
//        alert.tag=2;
//        [alert show];
//        
//        UIPasteboard *pasteboard=[UIPasteboard generalPasteboard];
//        //        然后，可以使用如下代码来把一个字符串放置到剪贴板上：
//        pasteboard.string = [arrInfoFoot objectAtIndex:1];
//        
//        
//    }
//}

- (void)loginSuccessfully{
    /*
#ifdef DHH_iOS
    
    UITabBarController *tabController = [[UITabBarController alloc] init];
    [tabController.tabBar setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"tabBarBG.png"]];
    [tabController.moreNavigationController.navigationBar setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"navigationBar.png"] forBarMetrics:UIBarMetricsDefault];
    
    SuitViewController *suit = [[SuitViewController alloc] init];
    UINavigationController *suitNav = [[UINavigationController alloc] initWithRootViewController:suit];
    [suitNav.navigationBar setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"navigationBar.png"] forBarMetrics:UIBarMetricsDefault];
    
    ProductViewController *product = [[ProductViewController alloc] init];
    UINavigationController *productNav = [[UINavigationController alloc] initWithRootViewController:product];
    [productNav.navigationBar setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"navigationBar.png"] forBarMetrics:UIBarMetricsDefault];
    
    StatisticViewController *statistic = [[StatisticViewController alloc] initWithNibName:nil bundle:nil tag:1];
    UINavigationController *statisticNav = [[UINavigationController alloc]
                                            initWithRootViewController:statistic];
    [statisticNav.navigationBar setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"navigationBar.png"] forBarMetrics:UIBarMetricsDefault];
    
    AnalysisViewController *analysis = [[AnalysisViewController alloc] init];
    UINavigationController *analysisNav = [[UINavigationController alloc] initWithRootViewController:analysis];
    [analysisNav.navigationBar setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"navigationBar.png"] forBarMetrics:UIBarMetricsDefault];
    
    StatisticViewController *statistic1 = [[StatisticViewController alloc] initWithNibName:nil bundle:nil tag:2];
    UINavigationController *statisticNav1 = [[UINavigationController alloc]
                                            initWithRootViewController:statistic1];
    [statisticNav1.navigationBar setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"navigationBar.png"] forBarMetrics:UIBarMetricsDefault];
    
    HelpViewController *help = [[HelpViewController alloc] init];
    UINavigationController *helpNav = [[UINavigationController alloc] initWithRootViewController:help];
    [helpNav.navigationBar setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"navigationBar.png"] forBarMetrics:UIBarMetricsDefault];
    
    NSArray *array = [NSArray arrayWithObjects:suitNav,productNav,analysisNav,statisticNav,statisticNav1,helpNav, nil];
    [tabController setViewControllers:array];
    [self.navigationController pushViewController:tabController animated:YES];
#else
     */
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    [def setObject:userTextField.text forKey:@"username"];
    [def setObject:passwordTextField.text forKey:@"password"];
    [def synchronize];
    
    if ([[[PMGlobal getInstance]gettype]isEqualToString:@"type1"]) {
        MainType1ViewController *mainView = [[MainType1ViewController alloc]init];
        [self.navigationController pushViewController:mainView animated:YES];
        [self textFieldShouldReturn:nil];
    }
    else
    {
        MainViewController *mainView = [[MainViewController alloc] init];
        [self.navigationController pushViewController:mainView animated:YES];
        [self textFieldShouldReturn:nil];
    }
    
//#endif
}

#pragma mark 隐藏navigationbar
-(void)hidden:(NSNotification *)sender
{
    self.navigationController.navigationBarHidden = YES;
    passwordTextField.text=@"";
}

-(CGRect)getScanCrop:(CGRect)rect readerViewBounds:(CGRect)readerViewBounds
{
    CGFloat x,y,width,height;
    
    x = rect.origin.x / readerViewBounds.size.width;
    y = rect.origin.y / readerViewBounds.size.height;
    width = rect.size.width / readerViewBounds.size.width;
    height = rect.size.height / readerViewBounds.size.height;
    
    return CGRectMake(x, y, width, height);
}

-(void)clearuser:(UIButton *)sender
{
    [WaitTooles showHUD:@"清除账号的绑定设备"];
    [[WebServiceManager sharedManager]cleardeviceid:userTextField.text completion:^(NSDictionary *response){
        [WaitTooles removeHUD];
    }];
}
@end
